package com.sfx.distributeLockStock.lock;

import com.sfx.distributeLockStock.dao.mapper.IMySQLLockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2024-02-06
 * Time: 15:40
 */
public class MySQLLock extends AbstractLock {

    private IMySQLLockMapper sqlLockMapper;
    private String lockName;

    //事务管理器
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    // 事务的一些基础信息，如超时时间、隔离级别、传播属性等
    @Autowired
    private TransactionDefinition transactionDefinition;
    private TransactionStatus transaction;

    public MySQLLock(IMySQLLockMapper sqlLockMapper, String lockName) {
        this.sqlLockMapper = sqlLockMapper;
        this.lockName = lockName;
    }

    @Override
    public void lock(Long expireTime) {

    }

    @Override
    public void lock() {
        while (true) {
            try {
                //TransactionStatus: 事务的一些状态信息，如是否是一个新的事务、是否已被标记为回滚
                transaction = platformTransactionManager.getTransaction(transactionDefinition);
                sqlLockMapper.selectLockForUpdate(lockName);
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void unlock() {
        platformTransactionManager.commit(transaction);
    }
}
